Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Returning reference to class needs a copy constructor? #94

Open
jwdevel opened this issue May 22, 2020 · 0 comments
Open

Returning reference to class needs a copy constructor? #94

jwdevel opened this issue May 22, 2020 · 0 comments

Comments

@jwdevel
Copy link

jwdevel commented May 22, 2020

I am writing a builder-style class.
This class is also not copyable.

I want to expose this class in Lua, with a similar builder-style interface.

However, if I have a builder method that returns \*this, kaguya has trouble binding it.
But if I change it to a pointer, using this, it works fine.

Not sure if it's a bug or what.
It seems like there should be a way to use a reference without making a copy.

Example code:

struct MyBuilder {
	MyBuilder(int n) : m_n(n) {}

	// No copies
	MyBuilder(const MyBuilder &) = delete;
	MyBuilder &operator=(const MyBuilder &) = delete;

	// pointer-style
	MyBuilder *increment_ptr() {
		++m_n;
		return this;
	}

	// reference-style
	MyBuilder &increment() {
		++m_n;
		return *this;
	}

	int build() { return m_n; }

private:
	int m_n;
};

int main() {
	kaguya::State state;

	// C++ usage of builder:
	// Using references (preferred)
	MyBuilder(100)
		.increment()
		.increment()
		.build();
	// Using pointers
	MyBuilder(100)
		.increment_ptr()
		->increment_ptr()
		->build();

	state["MyBuilder"].setClass(
		kaguya::UserdataMetatable<MyBuilder>()
			.setConstructors<MyBuilder(int)>()

			// OK
			.addFunction("increment_ptr", &MyBuilder::increment_ptr)

			// no joy. Compiler says:
			//    "use of deleted function ‘MyBuilder::MyBuilder(const MyBuilder&)’"
			//.addFunction("increment", &MyBuilder::increment)
		);

    return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant