Home > Backend Development > C++ > body text

Can Singleton Design Patterns Return References Instead of Pointers?

Patricia Arquette
Release: 2024-11-02 06:33:03
Original
611 people have browsed it

Can Singleton Design Patterns Return References Instead of Pointers?

Can Singleton Design Patterns Return References Instead of Pointers?

The conventional approach in C for creating a singleton involves returning a pointer to the instantiated object. However, an alternative technique is proposed: returning a reference instead.

This approach appears logical as it eliminates the responsibility of manually freeing the singleton object. The reason for this lies in the difficulty of determining who maintains a reference to the singleton, making it unwise to attempt manual deallocation.

Employing a static function method achieves both lazy initialization and ensures that the object is created and destroyed only once:

<code class="cpp">class S
{
    public:
        static S& getInstance()
        {
            static S    instance;
            return instance;
        }
    private:
        S() {}
        S(S const&);              // Don't Implement.
        void operator=(S const&); // Don't implement
 };</code>
Copy after login

Additionally, the constructor must be made private and the default copy constructor and assignment operator must be overridden to prevent copying and thus maintaining the singleton property.

However, it is crucial to note that this technique may not provide thread safety in all scenarios. In such cases, consider the following resources:

  • https://stackoverflow.com/a/1008289/14065
  • Singleton: How should it be used
  • C Singleton design pattern

Remember to carefully evaluate the reasons for utilizing a singleton to ensure it is the appropriate design choice.

The above is the detailed content of Can Singleton Design Patterns Return References Instead of Pointers?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!