0
votes

I encounter some strange behavior with shared_ptr and I can not explain why this happens:

std::shared_ptr<QueryQualification> qualification = query->getQualification();
if (qualification != nullptr) {
    // add selection
    std::shared_ptr<Operator> selection = std::shared_ptr<Operator>(new Selection(qualification));
    selection->setLeftChild(scan);
    ...
}

And here is the constructor of Selection which causes the segmentation fault:

class Selection : public Operator {
public:
   Selection(std::shared_ptr<QueryQualification> qualificiation) : qualification(qualification) { }
...
private:
   std::shared_ptr<QueryQualification> qualification;
};

I know, that I can improve the copy behavior with move semantics here, but I want to get some running code first.

The code above raises a segmentation fault in the constructor of Selection: The backtrace of the error

SelectionOperator.hpp (line 24) is the code line of the Selection constructor above.

I really don't understand what is happening here as the qualification object is perfectly valid before giving it to Selection as an argument.

Thanks in advance!

1
Is query null at this point? - BlamKiwi
No, query is valid as well. You can see that because std::shared_ptr<QueryQualification> qualification = query->getQualification(); would already lead to a segmentation fault otherwise. - moo
Yes, make_shared<T>(...) is potentially more efficient than shared_ptr<T>(new T(...)), because it can coalesce the two allocations (and corresponding deallocations). - Deduplicator
There seems to be a typo in spelling qualificiation in the constructor - davidc
@davidc It might improve readability, but it's not necessary; in qualification(qualification) the first name is unambiguously a member name, and the second takes from the current scope where the parameter name shadows the member. It will still do the right thing, even if it is confusing to read. Edit: Missed the misspelling, of course that will cause problems. :) - cdhowie

1 Answers

-1
votes
class Selection : public Operator {
public:
   Selection(std::shared_ptr<QueryQualification> qualification) : m_qualification(qualification) { }
...
private:
   std::shared_ptr<QueryQualification> m_qualification;
};