Skip to content

Returning reference to class needs a copy constructor? #94

@jwdevel

Description

@jwdevel

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;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions